package com.sac.approval.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sac.approval.domain.ApprovalDO;
import com.sac.approval.domain.ApprovalLineDO;
import com.sac.approval.domain.AttachmentDO;
import com.sac.approval.enums.ApprovalLineStatusEnum;
import com.sac.approval.enums.ApprovalStatusEnum;
import com.sac.approval.service.*;
import com.sac.approval.vo.ApItemVO;
import com.sac.common.annotation.AuthToken;
import com.sac.common.utils.*;
import com.sac.emp.service.EmpService;
import com.sac.system.service.UserService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author xiaodong
 * @title
 * @date 2019/1/22 14:08
 * @desc
 */
@RestController
@RequestMapping("/approval/sub/api/basic/v1.0")
public class WebApi {

    @Autowired
	private EmailService emailService;

	@Autowired
	private ApprovalService approvalService;

	@Autowired
	private ApprovalLineService approvalLineService;

	@Autowired
	private ApprovalTemplateService approvalTemplateService;

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	private UserService userService;

	@Autowired
	private EmpService empService;

	@Autowired
	private ApprovalQueryService approvalQueryService;

	@Autowired
	private DelegateMappingService delegateMappingService;

	/**
	 * 创建审批
	 * @param apItemVO
	 * @return
	 */
	@AuthToken
	@PostMapping("/submit/general")
	public Object general(@RequestBody ApItemVO apItemVO) {
		Date date = new Date();
		//master
		ApprovalDO app = new ApprovalDO();
		app.setAppId(DateFormatUtils.format(new Date(),"yyyyMMddhhmmssSSS"));
		app.setTitle(apItemVO.getApTtl());
		app.setContent(apItemVO.getTxtClobcn());
		app.setContType(apItemVO.getTxtTypeCd());
		app.setCharSet(apItemVO.getChsetCd());
		app.setSecretType(apItemVO.getApDocSecuTypeCd());
		app.setNotifyType(apItemVO.getNtfTypeCd());
		app.setUrgentType(apItemVO.getUrgYn());
		app.setCreateTime(date);
		app.setStatus(ApprovalStatusEnum.PENDING.getValue());
		//审批line
		List<ApprovalLineDO> appLines = new ArrayList<ApprovalLineDO>();
		if(apItemVO.getAapTaplnVOList()!=null){
			Arrays.asList(apItemVO.getAapTaplnVOList()).forEach(receiver -> {

				ApprovalLineDO appLine = new ApprovalLineDO();
				appLine.setAppId(app.getAppId());
				appLine.setHandleType(Integer.parseInt(receiver.getApRlCd()));
				if("0".equals(receiver.getApSeq())){
					appLine.setReceiptTime(date);
					appLine.setReadTime(date);
					appLine.setHandleTime(date);
					appLine.setRemark(apItemVO.getRemark());
					app.setCreateUser(receiver.getApRelrEpid());
				}
				appLine.setReceiverEpid(receiver.getApRelrEpid());
				//appLine.setReceiverMail(receiver.getAprelrmailaddr());
				appLine.setReceiverMail(empService.getEmpDetailInfo(receiver.getApRelrEpid()).getEmpMail());
				appLine.setSeq(Integer.parseInt(receiver.getApSeq()));
				appLine.setStatus(ApprovalLineStatusEnum.PENDING.getValue());
				appLine.setArbPmtYn(receiver.getArbPmtYn());
				appLine.setTxtMdfyPmtYn(receiver.getTxtMdfyPmtYn());
				appLine.setPathMdfyPmtYn(receiver.getPathMdfyPmtYn());
				appLine.setIsDelete("N");
				appLines.add(appLine);
			});
		}

		//附件
		List<AttachmentDO> attachments = new ArrayList<AttachmentDO>();
		if(apItemVO.getFiles()!=null) {
			Arrays.asList(apItemVO.getFiles()).forEach(file -> {

				String originFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\")+1).split("\\?")[0];

				String fileName = FileUtil.renameToUUID(originFileName);

				AttachmentDO attachment = new AttachmentDO();
				attachment.setAppId(app.getAppId());
				attachment.setFileName(fileName);
				attachment.setFileOriginName(originFileName);
				if(file.getSize() == 0L){
					attachment.setFileSize(Long.parseLong(file.getOriginalFilename().split("\\?").length > 1 ? file.getOriginalFilename().split("\\?")[1] : "0" ));
				}else {
					attachment.setFileSize(file.getSize());// B
				}
				attachment.setFileType(file.getContentType());

				attachments.add(attachment);
				try {
					// 上传附件
					//FileUtil.uploadFile(file.getBytes(), ResourceUtils.getURL("classpath:upload").getPath()+ File.separator,fileName);
					SftpUtil.uploadFile(file.getBytes(),fileName);
				} catch (Exception e) {
					e.printStackTrace();
					throw new BDException("文件上传失败");
				}
			});
		}
		//保存信息
		approvalService.createApproval(app, appLines,attachments);

		//获取后面的审批人列表
        List<ApprovalLineDO> pendingLineList = approvalQueryService.getPendingApproverList(app.getAppId());

		// 异步发送邮件和通知
		approvalService.pushPendingNotification(pendingLineList,app);
		approvalService.sendEmail(pendingLineList,app);
		return R.ok();
	}

	/**
	 * 创建审批
	 * @param apItemVO
	 * @return
	 */
	@AuthToken
	@PostMapping("/submit/withAttach")
	public Object withAttach(MultipartHttpServletRequest request) {
		List<MultipartFile> files = request.getFiles("fileInfo") ;
		String appBody =  request.getParameter("apItemVO");

		ApItemVO apItemVO = JSON.toJavaObject(JSON.parseObject(appBody),ApItemVO.class);

//		apItemVO.setFiles((MultipartFile[]) files);

		Date date = new Date();
		//master
		ApprovalDO app = new ApprovalDO();
		app.setAppId(DateFormatUtils.format(new Date(),"yyyyMMddhhmmssSSS"));
		app.setTitle(apItemVO.getApTtl());
		app.setContent(apItemVO.getTxtClobcn());
		app.setContType(apItemVO.getTxtTypeCd());
		app.setCharSet(apItemVO.getChsetCd());
		app.setSecretType(apItemVO.getApDocSecuTypeCd());
		app.setNotifyType(apItemVO.getNtfTypeCd());
		app.setUrgentType(apItemVO.getUrgYn());
		app.setCreateTime(date);
		app.setCreateUser(ShiroUtils.getEmpId().toString());
		app.setStatus(ApprovalStatusEnum.PENDING.getValue());
		//审批line
		List<ApprovalLineDO> appLines = new ArrayList<ApprovalLineDO>();
		if(apItemVO.getAapTaplnVOList()!=null){
			Arrays.asList(apItemVO.getAapTaplnVOList()).forEach(receiver -> {

				ApprovalLineDO appLine = new ApprovalLineDO();
				appLine.setAppId(app.getAppId());
				appLine.setHandleType(Integer.parseInt(receiver.getApRlCd()));
				if("0".equals(receiver.getApSeq())){
					appLine.setReceiptTime(date);
					appLine.setReadTime(date);
					appLine.setHandleTime(date);
					appLine.setRemark(apItemVO.getRemark());
				}
				appLine.setReceiverEpid(receiver.getApRelrEpid());
				appLine.setReceiverMail(receiver.getAprelrmailaddr());
				appLine.setSeq(Integer.parseInt(receiver.getApSeq()));
				appLine.setStatus(ApprovalLineStatusEnum.PENDING.getValue());
				appLine.setArbPmtYn(receiver.getArbPmtYn());
				appLine.setTxtMdfyPmtYn(receiver.getTxtMdfyPmtYn());
				appLine.setPathMdfyPmtYn(receiver.getPathMdfyPmtYn());
				appLine.setIsDelete("N");
				appLines.add(appLine);
			});
		}

		//附件
		List<AttachmentDO> attachments = new ArrayList<AttachmentDO>();
		if(apItemVO.getFiles()!=null) {
			Arrays.asList(apItemVO.getFiles()).forEach(file -> {

				String originFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\")+1).split("\\?")[0];

				String fileName = FileUtil.renameToUUID(originFileName);

				AttachmentDO attachment = new AttachmentDO();
				attachment.setAppId(app.getAppId());
				attachment.setFileName(fileName);
				attachment.setFileOriginName(originFileName);
				if(file.getSize() == 0L){
					attachment.setFileSize(Long.parseLong(file.getOriginalFilename().split("\\?").length > 1 ? file.getOriginalFilename().split("\\?")[1] : "0" ));
				}else {
					attachment.setFileSize(file.getSize());// B
				}
				attachment.setFileType(file.getContentType());

				attachments.add(attachment);
				try {
					// 上传附件
					//FileUtil.uploadFile(file.getBytes(), ResourceUtils.getURL("classpath:upload").getPath()+ File.separator,fileName);
					SftpUtil.uploadFile(file.getBytes(),fileName);
				} catch (Exception e) {
					e.printStackTrace();
					throw new BDException("文件上传失败");
				}
			});
		}
		//保存信息
		approvalService.createApproval(app, appLines,attachments);

		//获取后面的审批人列表
        List<ApprovalLineDO> pendingLineList = approvalQueryService.getPendingApproverList(app.getAppId());

		// 异步发送邮件和通知
		approvalService.pushPendingNotification(pendingLineList,app);
		approvalService.sendEmail(pendingLineList,app);
		return R.ok();
	}

	/**
	 * 创建审批
	 * @param apItemVO
	 * @return
	 */
	@AuthToken
	@PostMapping("/submit/withAttach2")
	public Object withAttach2(ApItemVO apItemVO) {
		Date date = new Date();
		//master
		ApprovalDO app = new ApprovalDO();
		app.setAppId(DateFormatUtils.format(new Date(),"yyyyMMddhhmmssSSS"));
		app.setTitle(apItemVO.getApTtl());
		app.setContent(apItemVO.getTxtClobcn());
		app.setContType(apItemVO.getTxtTypeCd());
		app.setCharSet(apItemVO.getChsetCd());
		app.setSecretType(apItemVO.getApDocSecuTypeCd());
		app.setNotifyType(apItemVO.getNtfTypeCd());
		app.setUrgentType(apItemVO.getUrgYn());
		app.setCreateTime(date);
		app.setCreateUser(ShiroUtils.getEmpId().toString());
		app.setStatus(ApprovalStatusEnum.PENDING.getValue());
		//审批line
		List<ApprovalLineDO> appLines = new ArrayList<ApprovalLineDO>();
		if(apItemVO.getAapTaplnVOList()!=null){
			Arrays.asList(apItemVO.getAapTaplnVOList()).forEach(receiver -> {

				ApprovalLineDO appLine = new ApprovalLineDO();
				appLine.setAppId(app.getAppId());
				appLine.setHandleType(Integer.parseInt(receiver.getApRlCd()));
				if("0".equals(receiver.getApSeq())){
					appLine.setReceiptTime(date);
					appLine.setReadTime(date);
					appLine.setHandleTime(date);
					appLine.setRemark(apItemVO.getRemark());
				}
				appLine.setReceiverEpid(receiver.getApRelrEpid());
				appLine.setReceiverMail(receiver.getAprelrmailaddr());
				appLine.setSeq(Integer.parseInt(receiver.getApSeq()));
				appLine.setStatus(ApprovalLineStatusEnum.PENDING.getValue());
				appLine.setArbPmtYn(receiver.getArbPmtYn());
				appLine.setTxtMdfyPmtYn(receiver.getTxtMdfyPmtYn());
				appLine.setPathMdfyPmtYn(receiver.getPathMdfyPmtYn());
				appLine.setIsDelete("N");
				appLines.add(appLine);
			});
		}

		//附件
		List<AttachmentDO> attachments = new ArrayList<AttachmentDO>();
		if(apItemVO.getFiles()!=null) {
			Arrays.asList(apItemVO.getFiles()).forEach(file -> {

				String originFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("\\")+1).split("\\?")[0];

				String fileName = FileUtil.renameToUUID(originFileName);

				AttachmentDO attachment = new AttachmentDO();
				attachment.setAppId(app.getAppId());
				attachment.setFileName(fileName);
				attachment.setFileOriginName(originFileName);
				if(file.getSize() == 0L){
					attachment.setFileSize(Long.parseLong(file.getOriginalFilename().split("\\?").length > 1 ? file.getOriginalFilename().split("\\?")[1] : "0" ));
				}else {
					attachment.setFileSize(file.getSize());// B
				}
				attachment.setFileType(file.getContentType());

				attachments.add(attachment);
				try {
					// 上传附件
					//FileUtil.uploadFile(file.getBytes(), ResourceUtils.getURL("classpath:upload").getPath()+ File.separator,fileName);
					SftpUtil.uploadFile(file.getBytes(),fileName);
				} catch (Exception e) {
					e.printStackTrace();
					throw new BDException("文件上传失败");
				}
			});
		}
		//保存信息
		approvalService.createApproval(app, appLines,attachments);

		//获取后面的审批人列表
        List<ApprovalLineDO> pendingLineList = approvalQueryService.getPendingApproverList(app.getAppId());

		// 异步发送邮件和通知
		approvalService.pushPendingNotification(pendingLineList,app);
		approvalService.sendEmail(pendingLineList,app);
		return R.ok();
	}


}
